fsp = require './fs-promises'
path = require 'path'
_ = require 'underscore'
Q = require 'q'

# string extension
String::startsWith ?= (s) -> @[...s.length] is s
String::endsWith   ?= (s) -> s is '' or @[-s.length..] is s


#root
# ┣components
# ┣models
# ┗templates
#
module.exports = (root, callback) ->
  fsp.readdir_safe path.resolve(root), (err, files) ->
    unless err
      Q.all  _.map files, (file) ->
        fsp.traverse_safe path.resolve(root,file,"js"), relative: true
        .then (all) ->
          # 将所有文件转化为require语句
          requires = _.map all, (each) ->
            each=each.replace /\\/g,"/"
            if each.endsWith('.html')
              return "require('text!./#{each}');"
            else if each.endsWith('.mustache')
              return "require('hgn!./#{each.replace('.mustache', '')}');"
            else if each.endsWith('.js')
              return "require('./#{each.replace('.js', '')}')"
          # 所有的组件
          components = _.chain all
          .filter (each) ->
            each.startsWith('components/')
          .map (each) ->
            {
                id: each.replace('components/', '').replace('.js', ''),
                name: each.replace('components/', '').replace('View.js', ''),
                url: '/builder/images/icon_textInput_normal.png'
            }
          .value()
          [requires,components]
      .then (results) ->
        componentsTotal = [];
        requiresTotal = [];
        for result in results
          re=result[0];
          com=result[1];
          for ar in com
              componentsTotal=componentsTotal.concat ar
          for r in re
            if r and  r.length >0
              requiresTotal = requiresTotal.concat r
        js = """
        define(function(require) {
          #{requiresTotal.join(';\n\r')};
          return #{JSON.stringify(componentsTotal)};
        });
        """
        callback(null, js)
      .catch (err) ->
        console.trace err
        callback(err)
      # js = """
      # define(function(require) {
      #   return #{JSON.stringify(componentsTotal)};
      # });
      # """
      #
